package zhengqc.union_find;

public class UnionFindUsingQuickFind implements UnionFind {
    private int[] IDs;

    public UnionFindUsingQuickFind(int size) {
        IDs = new int[size];
        for (int i = 0; i < size; ++i) {
            IDs[i] = i;
        }
    }

    private void rangeCheck(int index) {
        if (index < 0 || index >= IDs.length) {
            throw new IllegalArgumentException(index + " is out of bound!");
        }
    }

    private int find(int p) {
        rangeCheck(p);
        return IDs[p];
    }

    @Override
    public int getSize() {
        return IDs.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {
        int pID = find(p),
            qID = find(q);
        if (pID == qID) {
            return;
        }
        for (int i = 0; i < IDs.length; ++i) {
            if (IDs[i] == pID) {
                IDs[i] = qID;
            }
        }
    }
}
